package com.link.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.common.util.EncriptUtil;
import com.link.dao.AccountDAO;
import com.link.dao.RoleDAO;
import com.link.inout.AuthenticationOutput;
import com.link.po.Account;

public class AuthenticationServiceImpl implements AuthenticationService {

    public AuthenticationOutput verifyAccount(Account accountInput) {
        
        AuthenticationOutput output = new AuthenticationOutput();
        
        Account accountOutput = null;
        
        if(accountInput.isGroupFlg()) {
            accountOutput = accountDAO.find(accountInput.getId());
        } else {
            accountOutput = accountDAO.getAccountByName(accountInput.getName());
        }

        boolean valid = false;
        if (accountOutput != null) {
           if(StringUtils.isNotBlank(accountInput.getPassword())) {
               valid = EncriptUtil.sha256Encode(accountInput.getPassword()).equals(accountOutput.getPassword());
           } else if (StringUtils.isNotBlank(accountInput.getEncryptPassword())){
               valid = accountInput.getEncryptPassword().equals(accountOutput.getPassword());
           } else {
               //Emtpy.
           }
        }
        
        output.setValidFlg(valid);
        output.setAccount(accountOutput);
        
        return output;

    }
    
    public Account getAccountByName(String name) {
        return accountDAO.getAccountByName(name);
    }
    
    public List<Account> getAccountListByType(boolean groupFlg) {
        return accountDAO.getAccountListByType(groupFlg);
    }

    public void updateAccount(Account account) {
        accountDAO.update(account);
    }

    private AccountDAO accountDAO;
    private RoleDAO roleDAO;
    
    public AccountDAO getAccountDAO() {
        return accountDAO;
    }
    public void setAccountDAO(AccountDAO accountDAO) {
        this.accountDAO = accountDAO;
    }
    public RoleDAO getRoleDAO() {
        return roleDAO;
    }
    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }
}
